<template>
  <div class="condition" v-if="isShowTaskQA">
    <div class="top">
      <!--<h3 class="title"><span class="sign"></span><span class="text">查询条件</span></h3>-->
      <!--<affix :label="$t('qualityCheck.condition')"></affix>-->
      <div class="tem">
        <span class="temp">{{$t('qualityCheck.qualityTemplateClass')}}：</span>
        <el-radio checked>{{$t('qualityCheck.qualityTemplateClassCall')}}</el-radio>
      </div>
      <div class="tem">
        <span class="temp">{{$t('qualityCheck.taskTempl')}}：</span>
        <el-select style="margin-left: 42px;" v-model.trim="taskTemVal" @change="taskTemChange">
          <el-option
            v-for="(item, index) in qualityCheckTaskTemplates"
            :key="index"
            :label="item.TASK_NAME"
            :value="index">
          </el-option>
        </el-select>
        <!--<el-radio-group v-model.trim="taskTemVal" @change="taskTemChange" v-show="qualityCheckTaskTemplates.length!==0">-->
          <!--<el-radio size="mini"-->
                    <!--v-show="false"-->
                    <!--:label="-1">-->
          <!--</el-radio>-->
          <!--<el-radio size="mini"-->
            <!--v-for="(item, index) in qualityCheckTaskTemplates"-->
            <!--:label="index">-->
              <!--{{item.TASK_NAME}}-->
          <!--</el-radio>-->
        <!--</el-radio-group>-->
        <el-button class="addOrDel" @click="showAddTaskTemp"><i class="iconfont icon-zhankai"></i> <span>{{$t('qualityCheck.addTempl')}}</span></el-button>
        <el-button v-show="qualityCheckTaskTemplates.length !== 0" class="addOrDel" @click="removeTaskTemp"><i class="iconfont icon-guanbi"></i> <span>{{$t('qualityCheck.delTempl')}}</span></el-button>
        <el-button v-show="isShowRefresh === 'extraction'" class="addOrDel" @click="refreshTaskTemp"><i class="iconfont icon-shuaxin"></i> <span>{{$t('public.refreshExtraction')}}</span></el-button>
        <span class="ui-unfold-span" v-if="qualityCheckTaskTemplates.length !== 0">
          <span @click="isShowFold = false" v-show="isShowFold">{{$t('report.foldedContition')}} <i class="el-icon-arrow-up"></i></span>
          <span @click="isShowFold = true" v-show="!isShowFold">{{$t('report.unfoldedContition')}} <i class="el-icon-arrow-down"></i></span>
        </span>
      </div>
      <Unfold :title="unfoldTitle" :isShow="isShowFold" style="margin-bottom: 20px" v-if="qualityCheckTaskTemplates.length !== 0">
        <template slot="unfoldSlot">
          <div v-show="qualityCheckTaskTemplates.length !== 0 && taskTemVal !== -1" class="condition-temp-show-wrap">
            <!--任务模板-->
            <div class="condition-temp-show-call">
              <el-row class="task-elrow" :gutter="40" style="margin-top:0px;">
                <el-col :span="8" style="padding-right: 60px;">
                  <p class="wd100">{{$t('qualityCheck.taskName')}}：</p>
                  <div class="condition-temp-con condition-temp-con-first-line">
                    <span class="condition-temp-con-detail">{{curTaskTemp.taskName}}</span>
                  </div>
                </el-col>
                <el-col :span="8" style="padding-right:60px;">
                  <p class="wd100">{{$t('qualityCheck.quaTemp')}}：</p>
                  <div class="condition-temp-con">
                    <span class="condition-temp-con-detail">{{curTaskTemp.TaskTmplateName}}</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <p class="wd100">{{$t('qualityCheck.extractRules')}}：</p>
                  <div class="condition-temp-con">
                    <span class="condition-temp-con-detail" style="width: 70%">{{curTaskTemp.extractionRuleNum}}</span>
                    <span class="condition-temp-con-detail" style="width: 10%">{{curTaskTemp.taskNum}}</span>
                  </div>
                </el-col>
              </el-row>
              <el-row class="task-elrow" :gutter="40">
                <el-col :span="8" style="padding-right: 60px;">
                  <p class="wd100">{{$t('qualityCheck.checkWorker')}}：</p>
                  <div class="condition-temp-con">
                    <span class="condition-temp-con-detail">{{curTaskTemp.taskQaSpecialist}}</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <p class="wd100">{{$t('public.callLabel')}}：</p>
                  <div class="condition-temp-con" style="width:100%;">
                    <span class="condition-temp-con-detail" style="width: calc(100% - 40px)">{{curTaskTemp.qaLableOne}}</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <p class="wd100">{{$t('public.callTime')}}：</p>
                  <div class="condition-temp-con" style="width:100%;">
                    <span class="condition-temp-con-detail" style="width: calc(45% - 22px)">{{curTaskTemp.taskPickerStart}}</span>
                    <span style="margin-right: 10px;">{{$t('public.to')}}</span>
                    <span class="condition-temp-con-detail" style="width: calc(45% - 22px)">{{curTaskTemp.taskPickerEnd}}</span>
                  </div>
                </el-col>
              </el-row>
              <el-row class="task-elrow" :gutter="40">
                <el-col :span="8" style="padding-right: 60px;">
                  <p class="wd100">{{$t('public.satisfaction')}}：</p>
                  <div class="condition-temp-con condition-temp-con-first-line">
                    <span class="condition-temp-con-detail">{{curTaskTemp.investigate}}</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <p class="wd100">{{$t('call.callTime')}}：</p>
                  <div class="condition-temp-con">
                    <div class="condition-temp-con-detail" style="width: 39%">{{curTaskTemp.telStart}}<span class="second">{{$t('public.seconds')}}</span></div>
                    <span style="margin-right: 10px;">{{$t('public.to')}}</span>
                    <div class="condition-temp-con-detail" style="width: 39%">{{curTaskTemp.telEnd}}<span class="second">{{$t('public.seconds')}}</span></div>
                  </div>
                </el-col>
                <el-col :span="8" style="padding-right:55px;">
                  <p class="wd100">{{$t('public.queues')}}：</p>
                  <div class="condition-temp-con condition-temp-con-first-line">
                    <span style="width:100%;" class="condition-temp-con-detail" v-if="!curTaskTemp.taskSelectQueues.length"></span>
                    <el-tag size="medium" style="margin-right:6px;margin-bottom:4px;" v-else v-for="(taskConnectTypeItem, index) in curTaskTemp.taskSelectQueues" :key="index">
                      {{taskConnectTypeItem}}
                    </el-tag>
                  </div>
                </el-col>
              </el-row>
              <el-row class="task-elrow" :gutter="40">
                <el-col :span="8" style="padding-right: 60px;">
                  <p class="wd100">{{$t('call.callType')}}：</p>
                  <div class="condition-temp-con">
                    <span class="condition-temp-con-detail" v-if="!curTaskTemp.taskConnectType.length"></span>
                    <el-tag size="medium" style="margin-right:6px;margin-bottom:4px;" v-else v-for="(taskConnectTypeItem, index) in curTaskTemp.taskConnectType" :key="index">
                    {{taskConnectTypeItem}}
                  </el-tag>
                  </div>
                </el-col>
                <el-col :span="16" v-show="callAgentShow">
                  <p class="wd100">{{$t('qualityCheck.callAgent')}}：</p>
                  <div class="condition-temp-con condition-temp-con-last-line">
                    <span class="condition-temp-con-detail" v-if="!curTaskTemp.taskSelectAgents.length" style="width: 43%"></span>
                    <el-tag size="medium" style="margin-right:6px;margin-bottom:4px;" v-else v-for="(item, index) in curTaskTemp.taskSelectAgents" :key="index">
                      {{item}}
                    </el-tag>
                    <el-checkbox v-model="curTaskTemp.taskCheckbox" :disabled="true">{{$t('public.includeUnderAgent')}}</el-checkbox>
                  </div>
                </el-col>

              </el-row>
            </div>
          </div>
        </template>
      </Unfold>
      <div class="sub">
        <el-button :disabled="isShowRefresh === 'extraction'" type="primary" class="primary_btn" @click="searchTaskTemBtn">{{$t('public.search2')}}</el-button>
      </div>
      <affix :label="$t('public.searchResult')"></affix>
    </div>
    <div class="tables" v-show="qualityCheckTaskTemplates.length !== 0 && isShowRefresh !== 'extraction'" v-loading="loading">
      <div class="deploy">
        <div class="table-header-config">
          <i class="iconfont icon-peizhi"></i>
          <span class="tex" @click.stop="setHeaderConfig">{{$t('report.setHeaderConfig')}}</span>
        </div>
        <Pagination
          class="fr"
          :small="true"
          :currentPage="taskCurPage"
          :count="count"
          @turnPage="turnPage"
          :totalPage="Math.ceil(count/pageSize)"
        >
        </Pagination>
      </div>
      <el-table :data="tableData" size="mini">
        <el-table-column :label="$t('qualityCheck.taskName')" width="">
          <template scope="scope">
            <span>{{curTaskTemp.taskName}}</span>
          </template>
        </el-table-column>
        <el-table-column
          :width="item.name === 'OFFERING_TIME' ? '160' : ''"
          :show-overflow-tooltip="true"
          v-for="(item, index) in tableDataHeader.Config"
          :key="index"
          v-if="item.show === true"
          :prop="item.name"
          :label="item.displayname">
        </el-table-column>
        <el-table-column  :label="$t('public.operate')" width="160">
          <template scope="scope2">
            <el-button v-show="taskQaSpecialistId === currentUserId" @click="handle(scope2.row)" type="text" size="small">{{$t('qualityCheck.grade')}}</el-button>
            <!--<br v-if="taskQaSpecialistId === currentUserId">-->
            <el-button v-show="taskQaSpecialistId === currentUserId" @click="replacementRecord(scope2.row)" type="text" size="small">{{$t('qualityCheck.replacement')}}</el-button>
            <!--<br v-if="taskQaSpecialistId === currentUserId">-->
            <el-button type="text" @click="look(scope2.row._id)" size="small" >{{$t('qualityCheck.viewLook')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="text-align: center;padding: 20px;">
      <!--<span v-show="qualityCheckTaskTemplates.length === 0">{{$t('public.noData')}}</span><br/>-->
      <span v-show="isShowRefresh === 'extraction'">{{$t('public.extraction')}}</span><br/>
    </div>
    <!--<el-dialog :close-on-click-modal="false"  modal-append-to-body lock-scroll top="10%" :title="$t('qualityCheck.callQualityInfo')" :visible.sync="callDialogShow" class="score" @close="off">-->
      <call-grade :callDialogShow="callDialogShow" @close="off" :flagId="flagId" :currentItemCall = "this.currentItemCall"  :currentGrade = "{}"  :template = "this.template" @saveGrade="saveGrade" @nextGrade="nextGrade" :qcResectLabel="qcResectLabel" @off="off" @handle="handle" :refreshCallGrade="refreshCallGrade"></call-grade>
    <!--</el-dialog>-->
    <div class="looklog">
      <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :visible.sync="isShowlooklog" :title="title">
        <div class="tables">
          <div class="deploy">
            <div class="search-pagination">
              <pagination
                :small="paginationRecord.small"
                :currentPage="paginationRecord.currentPage"
                :count="countRecord"
                @turnPage="turnPageRecord"
                :totalPage="totalPageRecord"
              >
              </pagination>
            </div>
          </div>
          <el-table :data="recordList" style="width: 100%" size="mini">
            <el-table-column prop="user" :label="listenpp" width="">
            </el-table-column>
            <el-table-column prop="" label="" width="">
            </el-table-column>
            <el-table-column prop="time" :label="listenTime" width="">
            </el-table-column>
          </el-table>
        </div>
      </el-dialog>
    </div>
    <add-task-tem :addTaskData="addTaskData" @addTaskTem="addTaskTem"></add-task-tem>
    <!--配置表头-->
    <header-option v-show="isShowTableConfig" :show="isShowTableConfig" :option="headOptions" :type="tableConfigType" v-on:close="closeTableConfig"></header-option>
  </div>
</template>
<script>
  import {deepClone, getCache, getLabelName, isHasFunc} from '@/utils/m7Utils'
  import addTaskTem from '../base/addTaskTem'
  import CallGrade from './CallGrade'
  import Pagination from '@/components/public-modules/card/Pagination'
  import Affix from '../../../ui-modules/affix/Affix.vue'
  import Unfold from '../../../ui-modules/unfold/index.vue'
  import headerOption from '../../report/base/headerOption.vue'
  export default {
    name: 'random',
    props: {
      refresh: String
    },
    data () {
      return {
        loading: false,
        isSearchState: false,
        isShowRefresh: 'finish',    //  条件模板  是否抽取成功时  刷新按钮是否展示
        addTempSearch: false,
        beforeMountState: false,    //   beforemount 时 不查数据  避免各模块  数据冲突
        template: {},
        taskTempId: '',
        taskCurrentName: '',
        isShowTaskQA: false,
        isShowlooklog: false,    // 显示查看日志
        recordList: [],
        paginationRecord: {
          small: false,
          currentPage: 1
        },
        paginationCall: {
          small: false,
          currentPage: 1
        },
        taskTemVal: '',   //   任务模板  value
        qualityCheckTaskTemplates: [],  // 任务模板
        curConditionTemp: {},    //  当前被选中的 任务模板
        curTaskTemp: {  //  当前被选中的 任务模板
          taskName: '',         // 任务名称
          TaskTmplateName: '', // 质检模板
          taskTemplate: '',
          extractionRuleNum: '',
          taskNum: 0,
          taskConnectType: [],   // 呼叫类型
          taskPickerStart: '',
          taskPickerEnd: '',
          taskCheckbox: false,
          taskSelectQueues: [],    // 技能组
          taskQaSpecialist: '',     // 质检员
          investigate: '',    // 满意度
          taskSelectAgents: [],  // 通话座席
          qaLableOne: '',   // 录音内容分类
          qaLableShow: false
        },
        title: '',
        listenTime: '',
        listenpp: '',
        taskCurPage: 1,
        pageSize: 10,
        addTaskData: {    //    添加模板  dialog  传的数据
          isShow: false,
          qualityCheckTemplates: []
        },
        callDialogShow: false,     // 评分
        isSave: false,
        qcResectLabel: false,
        currentItemCall: {},
        refreshCallGrade: 0,
        currentUserId: '',       // 当前座席的ID
        taskQaSpecialistId: '',   // 当前质检id
        callAgentShow: false,    // 是否有显示座席信息权限
        selectedId: '',
        selectedCallId: '',
        callForm: {},
        flagId: 'task',
        countRecord: 0,
        totalPageRecord: 1,
        tableData: [],
        tableDataHeader: {
          Config: [{ 'order': '1', 'name': 'CALL_NO_SHOW', 'displayname': '主叫号码', 'show': true }, { 'order': '2', 'name': 'DISPOSAL_AGENT', 'displayname': '接听座席', 'show': true }, { 'order': '3', 'name': 'CALLED_NO_SHOW', 'displayname': '被叫号码', 'show': true }, { 'order': '4', 'name': 'CONNECT_TYPE_show', 'displayname': '呼叫类型', 'show': true }, { 'order': '5', 'name': 'ERROR_MEMO', 'displayname': '呼入技能组', 'show': true }, { 'order': '6', 'name': 'INVESTIGATE', 'displayname': '满意度', 'show': true }, { 'order': '7', 'name': 'OFFERING_TIME', 'displayname': '呼叫时间', 'show': true }]
        },
        unfoldTitle: [], // 展开收起标题
        isShowFold: true, // 展开收起标题
        isShowTableConfig: false,    //  配置表头
        headOptions: {},
        tableConfigType: 'quality_call_table_title'
      }
    },
    watch: {
      refresh (cur, old) {
        if (cur === 'task') {
//          this.searchTaskTemBtn()
        }
      }
    },
    methods: {
//      从缓存获取 质检模板
      fetchData () {
        let p1 = this.$store.dispatch('getCache', {type: 'qualityCheckTemplates'})
        let p2 = this.$store.dispatch('getCache', {type: 'qualityTasks'})
        let p3 = this.$store.dispatch('getCache', {type: 'agents'})
        let p4 = this.$store.dispatch('getCache', {type: 'callType'})
        let p5 = this.$store.dispatch('getCache', {type: 'queues'})
        let p6 = this.$store.dispatch('getCache', {type: 'options'})
        Promise.all([p1, p2, p3, p4, p5, p6]).then(() => {
          this.addTaskData.qualityCheckTemplates = this.$getCache('qualityCheckTemplates')
          this.$store.dispatch('getQualityTaskTemplates').then((res) => {
            if (res.success) {
              this.qualityCheckTaskTemplates = res.list
              if (this.qualityCheckTaskTemplates) {
//                this.taskTemVal = 0
//                this.taskTemChange(0)
                if (this.addTempSearch) {
                  this.taskTemVal = 0
                  this.taskTemChange(0)
                } else {
                  this.taskTemVal = 0
                  this.taskTemChange(0)
                }
              } else {
                this.$message.error(this.$t('qualityCheck.configureTasktempl'))
              }
              this.isShowTaskQA = true
            }
          })
        })
        this.currentUserId = this.$store.state.session.user._id
      },
//      刷新模板状态
      refreshTaskTemp () {
        this.$store.dispatch('refreshCallExtractionStatus', {type: 'task', templateId: this.taskTempId}).then(resp => {
          if (!resp.extractionStatus || resp.extractionStatus === 'finish') {
            this.searchByTaskTem()
            this.isShowRefresh = 'finish'
          }
        })
      },
      taskTemChange (index) {
        if (index === -1) {
          return
        }
        console.log(index)
        this.isSearchState = false
        let taskTemplateId = ''
        if (this.qualityCheckTaskTemplates[index]) {
          taskTemplateId = this.qualityCheckTaskTemplates[index]._id
          this.taskTempId = this.qualityCheckTaskTemplates[index]._id
          this.taskCurrentName = this.qualityCheckTaskTemplates[index].TASK_NAME
          //              判断任务模板  是否抽取完成
          this.isShowRefresh = 'finish'
          if (this.qualityCheckTaskTemplates[index].extractionStatus === 'extraction') { //  抽取中
            this.isShowRefresh = 'extraction'
            this.$store.dispatch('refreshCallExtractionStatus', {type: 'task', templateId: this.taskTempId}).then(resp => {
              if (!resp.extractionStatus || resp.extractionStatus === 'finish') {
                this.searchByTaskTem()
                this.isShowRefresh = 'finish'
              }
            })
          } else if (this.qualityCheckTaskTemplates[index].extractionStatus === 'unextraction') {  //  未抽取
//            任务模板暂时 没有此情况
          } else {
            this.taskCurPage = 1
            this.searchByTaskTem()
          }
        }
        if (taskTemplateId) {
          this.getTaskTemplate(taskTemplateId)
        }
      },
      searchByTaskTem () {
        let data = {}
        this.loading = true
        this.isSave = false
        data.pageSize = this.pageSize
        data.page = this.taskCurPage
        data.cdrId = 'quality_check_query_task'
        data.taskTemplate = this.taskTempId
        data.searchType = 'task'
        this.$store.dispatch('normalCallSearch', data).then((res) => {
          if (res.selectedId) {
            this.selectedId = res.selectedId
          }
          this.addTempSearch = false
          this.isSearchState = true
          this.loading = false
          const list = res.list || []
          if (list.length === 0) {
            if (!res.count) {
              // 第一页且count为0是不再发请求
              this.taskCurPage = 1
            } else {
              let page = Math.ceil(res.count / data.pageSize)
              this.turnPage(page)
              return false
            }
          }
          this.tableData = res.list
          this.tableDataHeader = res.tableHeader
        })
      },
      turnPage (pageNum) {
        this.taskCurPage = pageNum
        this.searchByTaskTem()
      },
      getinvestigate () {
        let options = this.$getCache('options')
        for (let i = 0; i < options.length; i++) {
          if (options[i].name && options[i].name === '满意度调查选项') {
            return options[i]
          }
        }
      },
      searchTaskTemBtn () {
        if (this.taskTemVal === -1) {
          this.$message.error(this.$t('qualityCheck.chooseTaskTem'))
          return
        }
        if (this.qualityCheckTaskTemplates.length === 0) {
          this.$message.error(this.$t('qualityCheck.configureTasktempl'))
          return
        }
        this.searchByTaskTem()
      },
      getTaskTemplate (data) {
        let qualityTasks = this.$getCache('qualityTasks')
        if (qualityTasks) {
          let tasks = qualityTasks
          for (let ind in tasks) {
            if (data === tasks[ind]._id) {
              let res = tasks[ind]
              this.callForm = res.query
              this.curTaskTemp.taskName = res.TASK_NAME
              let templates = this.addTaskData.qualityCheckTemplates
              for (let i = 0; i < templates.length; i++) {
                if (templates[i]._id === res.query.TASK_TEMPLATE) {
                  this.curTaskTemp.TaskTmplateName = templates[i].name
                  this.template = templates[i]
                }
              }
              // 录音标签
              this.curTaskTemp.qaLableOne = ''
              let callLabel = this.$getCache('callLabel')
              if (res.query.singleLabel) {
                for (let i in callLabel) {
                  if (callLabel[i]._id === res.query.singleLabel) {
                    this.curTaskTemp.qaLableOne = callLabel[i].name
                  }
                }
              } else if (res.query.multiLabel) {
                let multiLabel = res.query.multiLabel || []
                let labelStr = ''
                labelStr += getLabelName(multiLabel, callLabel, labelStr)
                labelStr = labelStr.substring(0, labelStr.length - 1)
                this.curTaskTemp.qaLableShow = true
                this.curTaskTemp.qaLableOne = labelStr
              } else {
                this.curTaskTemp.qaLableShow = false
              }
              // 抽取规则
              if (res.query.sample_selection_rule === 'per_num') {
                this.curTaskTemp.extractionRuleNum = this.$t('qualityCheck.numPerCapita')
                this.curTaskTemp.taskNum = res.query.count
              } else if (res.query.sample_selection_rule === 'entirety_num') {
                this.curTaskTemp.extractionRuleNum = this.$t('qualityCheck.wholeNumArticles')
                this.curTaskTemp.taskNum = res.query.count
              } else if (res.query.sample_selection_rule === 'per_percent') {
                this.curTaskTemp.extractionRuleNum = this.$t('qualityCheck.perCapitaPercentage')
                this.curTaskTemp.taskNum = res.query.percent
              } else {
                this.curTaskTemp.extractionRuleNum = this.$t('qualityCheck.wholeCapitaPercentage')
                this.curTaskTemp.taskNum = res.query.percent
              }

              // 呼叫类型
              this.curTaskTemp.taskConnectType = []
              if (res.query.CONNECT_TYPE) {
                let calllist = []
                let curConditionTempArr = []
                if (res.query.CONNECT_TYPE.indexOf(',') !== -1) {
                  calllist = res.query.CONNECT_TYPE.split(',')
                } else {
                  calllist.push(res.query.CONNECT_TYPE)
                }
                for (let j = 0; j < calllist.length; j++) {
                  let callType = this.$getCache('callType')
                  for (let i = 0; i < callType.length; i++) {
                    if (callType[i].code_value === calllist[j]) {
                      curConditionTempArr.push(callType[i].code_name)
                    }
                  }
                }
                this.curTaskTemp.taskConnectType = curConditionTempArr
              } else {
                this.curTaskTemp.taskConnectType = []
              }

              // 呼叫时间
              this.curTaskTemp.taskPickerStart = res.query.BEGIN_TIME
              this.curTaskTemp.taskPickerEnd = res.query.END_TIME
              // 是否包含下级
              if (res.query.includeSubordinate) {
                this.curTaskTemp.taskCheckbox = true
              } else {
                this.curTaskTemp.taskCheckbox = false
              }
              // 技能组
              if (res.query.QUEUE) {
                let list = []
                let queuesArr = []
                if (res.query.QUEUE.indexOf(',') !== -1) {
                  list = res.query.QUEUE.split(',')
                } else {
                  list.push(res.query.QUEUE)
                }
                for (let j = 0; j < list.length; j++) {
                  let queues = this.$getCache('queues')
                  for (let i = 0; i < queues.length; i++) {
                    if (queues[i].Exten === list[j]) {
                      queuesArr.push(queues[i].DisplayName)
                    }
                  }
                }
                this.curTaskTemp.taskSelectQueues = queuesArr
              } else {
                this.curTaskTemp.taskSelectQueues = []
              }

              // 质检员
              let agents = this.$getCache('agents')
              for (let i = 0; i < agents.length; i++) {
                if (agents[i]._id === res.query.QA_SPECIALIST) {
                  this.taskQaSpecialistId = res.query.QA_SPECIALIST
                  this.curTaskTemp.taskQaSpecialist = agents[i].displayName + '[' + agents[i].exten + ']'
                }
              }

              // 满意度
              this.curTaskTemp.investigate = ''
              let investigate = this.getinvestigate()
              let investiageNum = res.query.INVESTIGATE
              if (investiageNum === 'unevaluated') {
                this.curTaskTemp.investigate = '--' + this.$t('public.unevaluated') + '--'
              } else if (investiageNum) {
                for (let i = 0; i < investigate.options.length; i++) {
                  let invData = investigate.options[i]
                  for (let j = 0; j < invData.options.length; j++) {
                    if (invData.options[j].name === investiageNum) {
                      this.curTaskTemp.investigate = invData.name
                    }
                  }
                }
              } else {
                this.curTaskTemp.investigate = this.$t('qualityCheck.all')
              }

              // 通话座席
              this.curTaskTemp.taskSelectAgents = []
              if (res.query.selectedAgentList) {
                let list = []
                let selectAgentsArr = []
                if (res.query.selectedAgentList.indexOf(',') !== -1) {
                  list = res.query.selectedAgentList.split(',')
                } else {
                  list.push(res.query.selectedAgentList)
                }
                for (let j = 0; j < list.length; j++) {
                  let agents = this.$getCache('agents')
                  for (let i = 0; i < agents.length; i++) {
                    if (agents[i]._id === list[j]) {
                      selectAgentsArr.push(agents[i].displayName)
                    }
                  }
                }
                this.curTaskTemp.taskSelectAgents = selectAgentsArr
              } else {
                this.curTaskTemp.taskSelectAgents = []
              }
              // 通话时长
              this.curTaskTemp.telStart = res.query.CALL_TIME_LENGTH_BEGIN
              this.curTaskTemp.telEnd = res.query.CALL_TIME_LENGTH_END
//              this.searchByTaskTem()
//              if (!this.beforeMountState) {
//              }
//              this.beforeMountState = false
            }
          }
        }
      },
      look (_id) {
        this.paginationRecord.currentPage = 1
        this.countRecord = 0
        this.totalPageRecord = 0
        this.isShowlooklog = true
        this.queryRecordCallListenLog(_id, 1)
      },
      turnPageRecord (pageNum) {
        this.paginationRecord.currentPage = pageNum
        this.queryRecordCallListenLog(this.currentId, pageNum)
      },
      queryRecordCallListenLog (_id, page) {
        this.currentId = _id
        this.title = this.$t('qualityCheck.callQualityLookLog')
        this.listenpp = this.$t('qualityCheck.checkPeople')
        this.listenTime = this.$t('qualityCheck.checkTime1')
        this.$store.dispatch('queryRecordCallListenLog', {'CALL_SHEET_ID': _id, 'page': page, 'pageSize': 10}).then(() => {
          this.recordList = this.$store.state.qualityCheck.recordList.list
          this.countRecord = this.$store.state.qualityCheck.recordList.count
          this.totalPageRecord = Math.ceil(this.$store.state.qualityCheck.recordList.count / 10) || 0
          this.isShow = true
        })
      },
      handle (data) {
        this.currentIndex = 0
        for (let i = 0; i < this.tempList.length; i++) {
          if (this.tempList[i]._id === data._id) {
            this.currentIndex = i
            break
          }
        }
        if (data.REPEAT_CALL) {
          data.repeatCall = data.REPEAT_CALL === '48h' ? this.$t('call.repeatCall48h') : this.$t('call.repeatCall24h')
        } else {
          data.repeatCall = '--'
        }
        var num = this.tempList.length - this.currentIndex
        if (num < 5) {
          setTimeout(this.getMoreQualityTaskCall, 1000)
        }
        if (this.template.QUALITY_TYPE === 'qualityWebchat') {
          this.webchatDialogShow = true
          let self = this
          this.$store.dispatch('recordWebchatSessionLog', {_id: data._id})
          self.currentItem = data
        } else {
          this.$store.dispatch('recordListenLog', {CALL_SHEET_ID: data._id})
          this.callDialogShow = true
          this.qcResectLabel = true
          let self = this
          let pro1 = this.$store.dispatch('queryBusiness', {callId: data._id, customer: data.CUSTOMER_ID})
          let pro2 = this.$store.dispatch('getQualityedCheckCallSheet', {data: data._id})
          Promise.all([pro1, pro2]).then(([rep1, rep2]) => {
            this.recordFileName(data.FILE_SERVER, data.RECORD_FILE_NAME, data.PBX, function (url) {
              data.audio = url
              if (rep1 && rep1.length > 0) {
                data.busHistory = [rep1[0]]
              } else {
                data.busHistory = []
              }
              self.currentItemCall = data
              self.currentItemCall.LABELS = rep2.LABELS || []
              self.refreshCallGrade = Math.random()
            })
          })
//          this.$store.dispatch('queryBusiness', {callId: data._id, customer: data.CUSTOMER_ID}).then((res) => {
//            this.recordFileName(data.FILE_SERVER, data.RECORD_FILE_NAME, data.PBX, function (url) {
//              data.audio = url
//              if (res && res.length > 0) {
//                data.busHistory = [res[0]]
//              } else {
//                data.busHistory = []
//              }
//              self.currentItemCall = data
//              self.refreshCallGrade = Math.random()
//            })
//          })
        }
      },
      off () {
        let play = document.getElementById('quality-autoplay_' + this.flagId + '_old')
        if (play) {
          play.pause()
        }
        this.webchatDialogShow = false
        this.callDialogShow = false
        this.qcResectLabel = false
        if (this.isSave === true) {
          this.searchByTaskTem()
        }
      },
      getMoreQualityTaskCall () {
        let data = {}
        data.task_id = this.taskCurrentName
        this.$store.dispatch('getMoreQualityTaskCall', {data, tempList: this.tempList})
      },
      nextGrade () {
        this.isSave = true
        this.$store.commit('deleteGraded/qualityCheckTask', this.currentIndex)
        this.$store.commit('deleteGraded/qualityCheckTask', 1)
        if (this.tempList.length <= 0) {
          this.$message.success(this.$t('qualityCheck.allRatingFinish'))
          this.webchatDialogShow = false
          this.callDialogShow = false
          this.searchByTaskTem()
        } else {
          this.$message.success(this.$t('qualityCheck.nextGrade'))
          this.handle(this.tempList[0])
        }
      },
      saveGrade (gradeObj, SQlabel, monitorType) {
        this.isSave = true
        this.$store.commit('deleteGraded/qualityCheckTask', this.currentIndex)
        if (this.template.QUALITY_TYPE === 'qualityWebchat') {
          let data = deepClone(gradeObj)
          data._id = this.currentItem._id
          data.TEMPLATE = this.template._id
          data.values = gradeObj.obj
          let self = this
          this.$store.dispatch('saveWebchatSheetGrade', {data, currentItem: this.currentItem}).then((res) => {
            if (res && res.success) {
              self.webchatDialogShow = false
              this.$store.commit('deleteGraded/qualityCheckTask', 1)
              if (self.tempList.length <= 0) {
                self.$message.success(this.$t('qualityCheck.allRatingFinish'))
                this.searchByTaskTem()
              } else {
                self.$message.success(this.$t('qualityCheck.rateSuccessNext'))
                this.handle(self.tempList[0])
              }
            }
          })
        } else if (this.template.type === 'pass') {
          let data = {}
          data.CALL_SHEET_ID = this.currentItemCall.CALL_SHEET_ID
          gradeObj.config.amount = gradeObj.grade.amount
          data.QUALITY_GRADE = gradeObj.config
          data.COMMENTS = gradeObj.grade.COMMENT
          let GRADE_DATA = {}
          GRADE_DATA._id = this.currentItemCall._id
          GRADE_DATA.OFFERING_TIME = this.currentItemCall.OFFERING_TIME
          GRADE_DATA.DISPOSAL_AGENT = this.currentItemCall.DISPOSAL_AGENT
          GRADE_DATA.CALL_NO = this.currentItemCall.CALL_NO
          GRADE_DATA.CALLED_NO = this.currentItemCall.CALLED_NO
          GRADE_DATA.CONNECT_TYPE = this.currentItemCall.CONNECT_TYPE
          GRADE_DATA.ERROR_MEMO = this.currentItemCall.ERROR_MEMO
          GRADE_DATA.CALL_TIME_LENGTH = this.currentItemCall.CALL_TIME_LENGTH
          GRADE_DATA.FILE_SERVER = this.currentItemCall.FILE_SERVER
          GRADE_DATA.RECORD_FILE_NAME = this.currentItemCall.RECORD_FILE_NAME
          GRADE_DATA.INVESTIGATE = this.currentItemCall.INVESTIGATE
          GRADE_DATA.GRADE_AMOUNT = gradeObj.config
          GRADE_DATA.COMMENTS = gradeObj.COMMENT
          GRADE_DATA.TEMPLATE = this.template._id
          GRADE_DATA.SQ_LABEL = SQlabel
          GRADE_DATA.monitorType = monitorType
          GRADE_DATA.QC_SUBMIT = false  //   系统抽取 false   座席提交  true
          data.GRADE_DATA = GRADE_DATA
          data.SQ_LABEL = SQlabel
          data.MONITOR_TYPE = monitorType
          let self = this
          this.$store.dispatch('saveCallShellGrade', {data}).then((res) => {
            if (res && res.success) {
              self.callDialogShow = false
              self.qcResectLabel = false
              this.$store.commit('deleteGraded/qualityCheckTask', 1)
              if (self.tempList.length <= 0) {
                self.$message.success(this.$t('qualityCheck.allRatingFinish'))
                this.searchByTaskTem()
              } else {
                self.$message.success(this.$t('qualityCheck.rateSuccessNext'))
                this.handle(self.tempList[0])
              }
            }
          })
        } else {
          let data = {}
          data.CALL_SHEET_ID = this.currentItemCall.CALL_SHEET_ID
          data.QUALITY_GRADE = gradeObj.grade
          data.COMMENTS = gradeObj.COMMENT
          let GRADE_DATA = {}
          GRADE_DATA._id = this.currentItemCall._id
          GRADE_DATA.OFFERING_TIME = this.currentItemCall.OFFERING_TIME
          GRADE_DATA.DISPOSAL_AGENT = this.currentItemCall.DISPOSAL_AGENT
          GRADE_DATA.CALL_NO = this.currentItemCall.CALL_NO
          GRADE_DATA.CALLED_NO = this.currentItemCall.CALLED_NO
          GRADE_DATA.CONNECT_TYPE = this.currentItemCall.CONNECT_TYPE
          GRADE_DATA.ERROR_MEMO = this.currentItemCall.ERROR_MEMO
          GRADE_DATA.CALL_TIME_LENGTH = this.currentItemCall.CALL_TIME_LENGTH
          GRADE_DATA.FILE_SERVER = this.currentItemCall.FILE_SERVER
          GRADE_DATA.RECORD_FILE_NAME = this.currentItemCall.RECORD_FILE_NAME
          GRADE_DATA.INVESTIGATE = this.currentItemCall.INVESTIGATE
          GRADE_DATA.GRADE_AMOUNT = gradeObj.grade
          GRADE_DATA.COMMENTS = gradeObj.COMMENT
          GRADE_DATA.TEMPLATE = this.template._id
          GRADE_DATA.SQ_LABEL = SQlabel
          GRADE_DATA.monitorType = monitorType
          GRADE_DATA.QC_SUBMIT = false  //   系统抽取 false   座席提交  true
          data.SQ_LABEL = SQlabel
          data.MONITOR_TYPE = monitorType
          for (let i in gradeObj.obj) {
            GRADE_DATA[i] = gradeObj.obj[i]
          }
          data.GRADE_DATA = GRADE_DATA

          let self = this
          this.$store.dispatch('saveCallGradeForScore', {data}).then((res) => {
            if (res.success) {
              self.callDialogShow = false
              self.qcResectLabel = false
              // 删除tempList评价完的那个
              this.$store.commit('deleteGraded/qualityCheckTask', 1)
              if (self.tempList.length <= 0) {
                self.$message.success(this.$t('qualityCheck.allRatingFinish'))
                this.searchByTaskTem()
              } else {
                self.$message.success(this.$t('qualityCheck.rateSuccessNext'))
                this.handle(self.tempList[0])
              }
            }
          })
        }
      },
      recordFileName (server, name, pbx, callBack) {
        if (!server) {
          callBack('')
          return
        }
        if (server.indexOf('record.7moor.com') > -1 || server.indexOf('m7-record.oss-cn-hangzhou') > -1 || server.indexOf('aliyuncs.com') > -1) {
          server = 'https' + server.substr(server.indexOf(':'), server.length)
          callBack(server + '/' + name)
        } else if (document.location.protocol === 'https:') {
          if (pbx) {
            getCache('accountPbx', pbx, this, function (pbxObj) {
              if (pbxObj) {
                if (pbxObj.assDomain) {
                  let assDomain = pbxObj.assDomain
                  if (assDomain.substr(assDomain.length - 1, assDomain.length) === '/') {
                    assDomain = assDomain.substr(0, assDomain.length - 1)
                  }
                  server = assDomain
                }
              }
              callBack(server + '/' + name)
            })
          } else {
            callBack(server + '/' + name)
          }
        } else {
          callBack(server + '/' + name)
        }
      },
      showAddTaskTemp () {
        this.addTaskData.isShow = true
      },
      removeTaskTemp () {
        if (this.taskTemVal === -1) {
          this.$message.error(this.$t('qualityCheck.chooseTaskTem'))
          return
        }
        this.$confirm(this.$t('qualityCheck.stopCurrTask'), this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('removeQualityCheckTaskTemplates', {'taskTemplate': this.taskTempId}).then((res) => {
            if (res.success) {
              this.addTempSearch = true
              this.fetchData()
              this.$message({
                type: 'success',
                message: this.$t('km.deleteSucc')
              })
            } else {
              this.$message.error(this.$t('qualityCheck.taskTemplDelError'))
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: this.$t('km.cannelDel')
          })
        })
      }, // 移除模板
      addTaskTem (data) { // 添加模板
        if (data) {
          this.selectedId = data
        }
        this.addTempSearch = true
        this.fetchData()
      },
      replacementRecord (data) {
        if (this.selectedCallId === '') {
          this.selectedCallId = this.selectedId
        }
        this.$store.dispatch('replacementRecord', {selectedId: this.selectedCallId, _id: data._id}).then((res) => {
          if (!res.success) {
            this.$message.error(this.$t('qualityCheck.replacementDataError'))
          } else {
            if (res.callId) {
              this.selectedCallId += ',' + res.callId
            } else {
              this.$message.error(this.$t('qualityCheck.noMoreCalls'))
              return
            }
            this.$message({
              message: this.$t('qualityCheck.replacementSucc'),
              type: 'success'
            })
            this.searchByTaskTem()
          }
        })
      },
      setHeaderConfig () {
        if (this.template.QUALITY_TYPE !== 'qualityWebchat') {
          this.$store.dispatch('getReportTableHeader', 'quality_call_table_title').then((res) => {
            this.headOptions = res
            this.tableConfigType = 'quality_call_table_title'
            this.isShowTableConfig = !this.isShowTableConfig
          })
        } else {
          this.$store.dispatch('getReportTableHeader', 'quality_webchat_table_title').then((res) => {
            this.headOptions = res
            this.tableConfigType = 'quality_webchat_table_title'
            this.isShowTableConfig = !this.isShowTableConfig
          })
        }
      },
      closeTableConfig (data) {
        this.isShowTableConfig = false
        if (data === 'save') {
          this.searchTaskTemBtn()
        }
      }
    },
    computed: {
      count () {
        return this.$store.state.qualityCheck.searchListTask.count
      },
      totalPage () {
        return Math.ceil(this.$store.state.qualityCheck.searchListTask.count / 10) || 1
      },
      tempList () {
        return this.$store.state.qualityCheck.tempListTask
      }
    },
    components: {
      addTaskTem,
      Pagination,
      CallGrade,
      Affix,
      Unfold,
      headerOption
    },
    beforeMount () {
      this.beforeMountState = true
      this.fetchData()
      if (isHasFunc('func_call_quality_agent', this.$store.state.session.user)) {
        this.callAgentShow = true
      }
    },
    activated () {
//      this.taskTemVal = -1
//      this.isSearchState = false
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .condition
    height calc(100vh - 158px)
    padding 20px 20px 0
    overflow scroll
    .ui-affix
      /*padding-bottom 0*/
      margin-top 20px
    .wd100
      width 100px
      text-align left
      display inline-block
      margin-bottom 6px
    .w200
      width 200px
    .task-elrow
      margin-top 20px
    .top
      .tem
        .addOrDel
          margin-left 20px
          display inline-block
          padding 4px
          border-radius 2px
          font-size 12px
          cursor pointer
          .iconfont
            font-size 12px
      .temp
        display inline-block
        margin-bottom 20px
      .el-radio
        margin 0 0 0 20px
      .temp
        color $cf-gray1
      .condition-temp-show-wrap
        .condition-temp-show-webchat
        .condition-temp-show-call
          .condition-temp-con
            display inline-block
            width 100%
            .condition-temp-con-detail
              display inline-block
              width 100%
              border 1px solid #ddd
              border-radius 4px
              background-color #fafafa
              padding 6px
              height 16px
              line-height 16px
              margin-right 10px
              vertical-align middle
              text-overflow ellipsis
              overflow hidden
              white-space  nowrap
            .con-lable
              padding 4px
              background-color $c-main
              color $cf-white
              border-radius 4px
              margin-right 5px
            .wd60
              width 60px
            .wd70
              width 70px
          .condition-temp-con-first-line
            min-width 280px
          .condition-temp-con-last-line
            /*width 600px*/
            /*.el-checkbox*/
              /*margin-left 20px*/
      .sub
        text-align right
        margin-top 20px
        .rest
        .search
          display inline-block
          width 90px
          height 30px
          cursor pointer
        .search
          margin-left 24px
    .tables
      padding-bottom 30px
      .deploy
        height 48px
        line-height 48px
        color #989898
        border 1px solid #ebebeb
        border-bottom none
        padding-left 14px
        .fr
          padding-top 10px
          height 38px
        .table-header-config
          float left
          line-height 42px
          .iconfont
            font-size 18px
            color $c-main
            float left
          .tex
            cursor pointer
            margin-left 10px
            color #000
    .title
      color $cf-level2
      margin 28px 0 18px 0
      font-weight normal
      position relative
      line-height 16px
      .sign
        position relative
        width 12px
        height 12px
        background #7ccdd1
        display inline-block
        z-index 3
      .text
        position relative
        display inline-block
        padding 0 8px 0 10px
        background $cf-white
        z-index 3
      &:after
        content ""
        display inline-block
        width 100%
        left 0
        border-bottom 1px dashed $cf-level2
        position absolute
        top 50%
  .second
    float right
  .search-pagination
    float right
    height 48px
    .page
      margin-top 10px
      .el-pagination
        padding 0
  .ui-unfold-span
    cursor pointer
    color $c-main
    margin-left 20px
</style>
